<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class ProductKey extends Eloquent{

	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'product_key';
	protected $validator = null;

	public function saveData($data){
		$product_key = new ProductKey;

		if(isset($data['id']) && $data['id'] > 0){
			$product_key = ProductKey::firstOrNew(array('id' => $data['id']));
		}

		$product_key->key        = $data['key'];
		$product_key->product_id = $data['product_id'];
		$product_key->save();
		Cache::forget('product_key-all-data');
		
		return $product_key;
	}

	public function getAllData(){
		if(!Cache::has('product_key-all-data')){
			$data = ProductKey::all();
			Cache::put('product_key-all-data', $data, 30);
		}

		$data = Cache::get('product_key-all-data');

		return $data;
	}

	public function validator($data){
		$id = (isset($data['id']))? $data['id'] : "NULL";

		$rules = array(
			'key'        => array('required', 'unique:product_key,key,' . $id . ',id,deleted_at,NULL'),
			'product_id' => array('numeric'),
			);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getErrorMessages(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}
